#!/bin/sh
# filename: dget
# description: get all DICOM datasets when given an ID
# input: cid, directory to save data
# Toan Nguyen, June 2012

#     Copyright © 2012-2013 Toan Nguyen <toan.nguyen@monash.edu>
#
#     This file is part of Xglom.
# 
#     This is free software: you can redistribute it and/or modify
#     it under the terms of the GNU General Public License as published by
#     the Free Software Foundation, either version 3 of the License, or
#     (at your option) any later version.
# 
#     This is distributed in the hope that it will be useful,
#     but WITHOUT ANY WARRANTY; without even the implied warranty of
#     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#     GNU General Public License for more details.
# 
#     You should have received a copy of the GNU General Public License
#     along with this program.  If not, see <http://www.gnu.org/licenses/>.

# check if arguments (command) are specified
if [[ $# -eq 0 ]]; then
	echo "Error: no argument is specified."
	exit 1
fi

# ========= MAIN SCRIPT ============

# check system first
. dcheck

#parse parameter
#example: ASSET_CID=1008.2.3.65.1.1
#example: DEST_DIR=/tmp

until [ -z "$1" ]
do
    case "$1" in
        "-c" | "-cid" )
        ASSET_CID=$2
        shift
        ;;
        "-d" | "-directory" )
        DEST_DIR=$2
        shift
        ;;
        * )
        shift
        ;;
    esac
done

if [ -z $ASSET_CID ]
then {
    echo "Error: must input asset cid"
    exit 1;
}
fi

if [ -z $DEST_DIR ]
then {
    echo "Error: must input destination directory"
    exit 1;
}
fi

if [ ! -d $DEST_DIR ]
then {
    echo "Directory doesn't exist. Create $DEST_DIR"
    mkdir -p ${DEST_DIR}

    if [ ! -d ${DEST_DIR} ]
    then {
        echo "Error: cannot create directory $DEST_DIR"
        exit 1
    }
    fi
}
fi

# download DICOM data 
# if ASSET_CID is a dataset cid, user "=" instead of "starts with"
#for id in $($MFCOMMAND asset.query :where "mf-dicom-series has value and ( cid starts with '$ASSET_CID' )" | awk '{print $4}' | tr -d \"); 
for id in $($MFCOMMAND asset.query :where "mf-dicom-series has value and ( cid = '$ASSET_CID' )" | awk '{print $4}' | tr -d \");
do 
    $MFCOMMAND asset.get :id ${id} :out file:$DEST_DIR/${id}.zip;
    unzip -d ${DEST_DIR}/"${ASSET_CID}" ${DEST_DIR}/${id}.zip;
    rm ${DEST_DIR}/${id}.zip;
done
